<?php
namespace Platform\Domain;

use Platform\Common\Functions;
use Platform\Model\SystemMenu as MenuModel;
use Platform\Model\SystemMenuRole as SystemMenuRoleModel;
use Platform\Model\SystemMenu as SystemMenuModel;
use Platform\Model\AdminRole as AdminRoleModel;
use Platform\Model\SystemProject as SystemProjectModel;
use PhalApi\Exception\BadRequestException;

class Roles extends Functions{

    //获取角色列表
    public function rolesList($where,$select,$order,$page,$perpage) {
        $model = new AdminRoleModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $data = array();
        //需要判断是不是超级管理员，如果不是需要筛选出自己和自己创建的人的数据
        if( $this->tokenData['role_name'] != '超级管理员' ){
            $where['add_who = ? or id = ?'] = array($this->tokenData['id'],$this->tokenData['role_id']);
        }
        $where['delete_flag'] = 'N';
        $where['not id'] = array(1);
        $count = $model->count($where,'id');
        $list = $model->getList($where,array(),$select,$order,$page,$perpage);
        if( !empty( $list ) ){
            //查询角色关联的菜单名称
            foreach ( $list as $k => $v ){
                $menu = '';
                $info = $SystemMenuRoleModel->getRoleMenuList(array('mr.role_id'=>$v['id']),'m.title,m.parent_id','m.sort_num ASC');
                if( !empty( $info ) ){
                    foreach ( $info as $kk => $vv ){
                        //父级不需要展示
                        if( $vv['parent_id'] == 0 ){
                            continue;
                        }
                        if( empty( $menu ) ){
                            $menu = $vv['title'];
                        }else{
                            $menu .= ','.$vv['title'];
                        }
                    }
                }
                //判断当前账号是不是自己的，是自己的不允许删除，编辑也只能修改名称
                if( $v['id'] == $this->tokenData['role_id'] ){
                    $list[$k]['is_self'] = 1;
                }else{
                    $list[$k]['is_self'] = 0;
                }
                $list[$k]['menu'] = $menu;
            }
        }
        $data['items'] = $list;
        $data['total'] = $count;
        return $data;
    }

    //添加角色
    public function addRoles($insertData){
        $model = new AdminRoleModel();
//        $SystemProjectModel = new SystemProjectModel();
        $SystemMenuModel = new SystemMenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        //角色名称不能重复
        $role_info = $model->getData(array('role_name'=>$insertData['role_name']),array(),'id,role_name');
        if( !empty( $role_info ) ){
            throw new BadRequestException('该角色名称已存在，请更换名称！');
        }
        //添加到角色表中
        $menu_list = $insertData['menu_list'];
        unset($insertData['menu_list']);
        //获取固定的参数
        $insertData = $this->selfAddFields($insertData);
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->insert($insertData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('角色添加错误，请联系管理员！');
        }
        //添加菜单角色关联关系
        $allInsertData = array();
        $n = 0;
        foreach ( $menu_list as $k => $v ){
            //查询菜单的父级
            $info = $SystemMenuModel->getData(array('id'=>$v),array(),'parent_id');
            if( empty( $info ) || $info['delete_flag']=='Y' ){
                throw new BadRequestException('菜单不存在，请刷新后重试！');
            }
            if( !in_array($info['parent_id'],$menu_list) && $info['parent_id'] != 0 ){
                $allInsertData[$n]['menu_id'] = $info['parent_id'];
                $allInsertData[$n]['role_id'] = $res;
                $allInsertData[$n]['parent_id'] = $info['parent_id'];
                $n++;
            }
            $allInsertData[$n]['menu_id'] = $v;
            $allInsertData[$n]['role_id'] = $res;
            $allInsertData[$n]['parent_id'] = $info['parent_id'];
            $n++;
        }
        //去重
        $allInsertData = $this->uniquArr($allInsertData,'menu_id');
        //添加到关联表中
        $res = $SystemMenuRoleModel->insertMore($allInsertData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('同步角色菜单失败，请联系管理员');
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }

    //获取菜单详情
    public function rolesDetail($id,$select){
        $model = new AdminRoleModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $detail = $model->getData(array('id'=>$id),array(),$select);
        if( empty($detail)||$detail['delete_flag']=='Y' ){
            throw new BadRequestException('菜单不存在或已删除！');
        }
        //菜单要选中的值一维数组形式
        $menu = $SystemMenuRoleModel->getList(array('role_id'=>$id));
        $menu_ids = array();
        if( !empty( $menu ) ){
            foreach ( $menu as $k => $v ){
                //要过滤父级id和menuid一样的数据
                if( $v['menu_id'] != $v['parent_id'] ){
                    $menu_ids[] = $v['menu_id'];
                }
            }
        }
        $detail['ids'] = $menu_ids;
        //获取菜单
        $model = new MenuModel();
        if( $this->tokenData['role_id'] != 1 ){
            $where = array('mr.role_id'=>$this->tokenData['role_id']);
            $select = 'm.id,m.id as authorityId,m.title,m.name,m.sort_num,m.parent_id as parentId,m.icon,m.path,m.url,m.depth';
            $order = 'm.parent_id, m.sort_num';
            $menus = $SystemMenuRoleModel->getRoleMenuList($where,$select,$order);
            //如果跟自己的id相同，全部设置disable
            foreach ( $menus as $k => $v ){
                if( $this->tokenData['role_id'] == $id ){
                    $menus[$k]['disabled'] = true;
                }else{
                    $menus[$k]['disabled'] = false;
                }
            }
        }else{
            $menus = $model->listAllMenus();
        }
        //根据parentId分子类
        $menus = $this->_getTree($menus);
        $detail['menus'] = $menus;
        return $detail;
    }

    //编辑提交角色
    public function updateRoles($id,$updateData){
        $model = new AdminRoleModel();
        $SystemMenuModel = new SystemMenuModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        //查询当前角色是否已存在
        $roleData = $model->getData(array('role_name'=>$updateData['role_name']),array(),'role_name,id,delete_flag');
        if( !empty($roleData)&&$roleData['delete_flag']=='N'&&$roleData['id'] != $id ){
            throw new BadRequestException('该角色名称已存在！');
        }
        //①修改数据到角色表
        $menu_list = $updateData['menu_list'];
        unset($updateData['menu_list']);
        //获取固定的参数
        $updateData = $this->selfEditFields($updateData);
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->update($id,$updateData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('角色编辑提交错误，请联系管理员！');
        }
        //②删除该角色之前所有的权限
        $res = $SystemMenuRoleModel->deleteAll(array('role_id'=>$id));
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('同步角色失败，请联系管理员');
        }
        //添加菜单角色关联关系
        $allInsertData = array();
        $n = 0;
        foreach ( $menu_list as $k => $v ){
            //查询菜单的父级
            $info = $SystemMenuModel->getData(array('id'=>$v),array(),'parent_id');
            if( empty( $info ) ){
                throw new BadRequestException('菜单不存在，请刷新后重试！');
            }
            if( !in_array($info['parent_id'],$menu_list) && $info['parent_id'] != 0 ){
                $allInsertData[$n]['menu_id'] = $info['parent_id'];
                $allInsertData[$n]['role_id'] = $id;
                $allInsertData[$n]['parent_id'] = $info['parent_id'];
                $n++;
            }
            $allInsertData[$n]['menu_id'] = $v;
            $allInsertData[$n]['role_id'] = $id;
            $allInsertData[$n]['parent_id'] = $info['parent_id']?$info['parent_id']:$v;
            $n++;
        }
        //去重
        $allInsertData = $this->uniquArr($allInsertData,'menu_id');
        //添加到关联表中
        $res = $SystemMenuRoleModel->insertMore($allInsertData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('同步角色菜单失败，请联系管理员');
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }

    //删除
    public function deleteRoles($id){
        $model = new AdminRoleModel();
        $SystemMenuRoleModel = new SystemMenuRoleModel();
        $info = $model->getData(array('id'=>$id));
        if( empty( $info ) ){
            throw new BadRequestException('数据不存在！');
        }
        if( $info['delete_flag'] =='Y' ){
            throw new BadRequestException('数据已被删除！');
        }
        //获取固定的参数
        $updateData = $this->selfDeleteFields(array());
        //因为涉及数据表多步操作，所以要开启事务
        \PhalApi\DI()->notorm->beginTransaction('db_master');
        $res = $model->updateAll(array('id'=>$id),$updateData);
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('数据删除有误，请联系管理员！');
        }
        //删除菜单关联的角色信息
        $res = $SystemMenuRoleModel->deleteAll(array('role_id'=>$id));
        if( $res === false ){
            \PhalApi\DI()->notorm->rollback('db_master');//回滚
            throw new BadRequestException('同步角色菜单删除失败，请联系管理员');
        }
        \PhalApi\DI()->notorm->commit('db_master');//提交
        return $res;
    }
}
